const BASE_URL = "http://38.147.173.37/cbserver";
// const BASE_URL = "http://localhost:8000";

export type RequestMethod = "GET" | "POST" | "PUT" | "DELETE" | "PATCH";

export async function httpClient<T>(
    endpoint: string,
    method: RequestMethod = "GET",
    data?: any,
    customHeaders?: HeadersInit
): Promise<T> {
    const userId = localStorage.getItem('userId');
    if (!userId) {
        throw new Error('User ID not found. Please select a role first.');
    }

    // 为所有请求添加 user_id 查询参数
    let url = `${BASE_URL}${endpoint}`;
    url += endpoint.includes('?') ? `&user_id=${userId}` : `?user_id=${userId}`;

    const headers: HeadersInit = {
        ...customHeaders,
    };

    const options: RequestInit = {
        method,
        headers,
    };

    if (data) {
        if (data instanceof FormData) {
            options.body = data;
        } else {
            options.body = JSON.stringify(data);
            options.headers = {
                ...options.headers,
                "Content-Type": "application/json",
            };
        }
    }

    const response = await fetch(url, options);
    if (!response.ok) {
        const errorResponse = await response.json();
        throw new Error(errorResponse.message || "请求失败");
    }
    return response.json();
}